/* eslint-disable import/first */
import React, { PureComponent, } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, } from 'react-native';
import * as BaseActions from '../../../app/actions/base';
import SubmitSelector from '../../../app/selectors/submit';
import connect from '../../../app/store/connect';
import ImagePicker from 'react-native-image-picker';
import { POST, } from '../../../commons/utils/request';
import urls from '../../../app/constants/urls';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingVertical: 10,
    // alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  button: {
    width: 100,
    height: 32,
    backgroundColor: '#4A4C5B',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 2,
    marginVertical: 12,
  },
  buttonText: {
    textAlign: 'center',
    fontSize: 15,
    color: '#fff',
  },
});

@connect(SubmitSelector, BaseActions)
export default class ImageViewPicker extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      resourcePath: {},
      imgUrl: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    console.log('TAGGG', `componentWillReceiveProps====image==${JSON.stringify(nextProps)}`);
    if (nextProps && nextProps.imgUrl) {
      this.setState({
        imgUrl: nextProps.imgUrl,
      });
    }
  }

  selectFile = () => {
    const options = {
      title: 'Select Image',
      customButtons: [
        {
          name: 'customOptionKey',
          title: 'Choose file from Custom Option',
        },
      ],
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };
    ImagePicker.showImagePicker(options, res => {
      console.log('Response = ', res);
      if (res.didCancel) {
        console.log('User cancelled image picker');
      } else if (res.error) {
        console.log('ImagePicker Error: ', res.error);
      } else if (res.customButton) {
        console.log('User tapped custom button: ', res.customButton);
        alert(res.customButton);
      } else {
        const source = res;
        this.setState({
          resourcePath: source,
        });
        uploadFile(`data:image/jpeg;base64,${this.state.resourcePath.data}`);
      }
    });

    const uploadFile = async (content) => {
      // await saveToken('111111');
      // const token = await getToken();
      // if (!token) {
      //   return;
      // }
      // const sBoundary = `--------${Date.now().toString(16)}`;

      this.props.actions.submitOption({ imgUploadTime: new Date().getTime(), });
      await POST(urls.uploadFile, JSON.stringify({
        fileType: 3,
        needOcr: false,
        content,
      }), {}, {
        // 'Content-Type': (`multipart/form-data; boundary=${sBoundary}`),
      }).then(resp => {
        console.log('TAGGG', `upload fifle====resp==${JSON.stringify(resp)}`);
        if (resp && resp.code === 0 && resp.data) {
          const id = resp.data.fileId;
          const url = resp.data.fileUrl;
          this.props.OnImageId(id);
        }
      });
    };
  }
  render() {
    return (
      <View style={styles.container}>
        { this.state.resourcePath.uri || this.state.imgUrl ? (<Image
          source={{
            uri: this.state.imgUrl ? this.state.imgUrl : `data:image/jpeg;base64,${this.state.resourcePath.data}`,
          }}
          style={{ width: 100, height: 100, }}
        />) : null }
        {/* <Image
            source={{ uri: this.state.resourcePath.uri, }}
            style={{ width: 200, height: 200, }}
          /> */}
        <TouchableOpacity onPress={this.selectFile} style={styles.button} >
          <Text style={styles.buttonText}>上传文件</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
